package com.dragon.dragonshop.controller.user;

import com.dragon.dragonshop.pojo.User;
import com.dragon.dragonshop.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserLoginController {

    @Autowired
    UserService userService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @PostMapping("/login")
    public String userLogin(@RequestParam("username") String username, @RequestParam("password") String password,
                            @RequestParam("verifyCode") String verifyCode, HttpSession session, HttpServletResponse response, boolean check,
                            HttpServletRequest request) throws UnsupportedEncodingException {
        String Code = (String) session.getAttribute("verifyCode");
        if (!StringUtils.isEmpty(Code)){
            if (!Code.equals(verifyCode)) {
                logger.warn("验证码出错!");
                return "redirect:/index.html";
            }
        }
        if(!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(password)) {
            logger.info("处理了" + username + "登录请求");
            User user = new User();
            user.setUserName(username);
            user.setPassword(password);
            boolean b = userService.checkUser(user);
            if (b == true) {
                session.setAttribute("user", username);
                if(check) {
                    String codeName = URLEncoder.encode(username, "UTF-8");
                    Cookie usernameCookie = new Cookie("rememberName", codeName);
                    Cookie passwordCookie = new Cookie("rememberPass", password);
                    usernameCookie.setPath(request.getContextPath() + "/");
                    passwordCookie.setPath(request.getContextPath()+"/");
                    usernameCookie.setMaxAge(10*24*60*60);
                    passwordCookie.setMaxAge(10*24*60*60);
                    response.addCookie(usernameCookie);
                    response.addCookie(passwordCookie);
                }
                logger.info(username + "用户已登录成功!");
            }else {
                logger.warn("用户登录失败!");
            }
        }else {
            logger.warn("用户名密码不能为空!");
        }
        return "redirect:/index.html";
    }

    @GetMapping("/logout")
    public String userLogout(HttpSession session,HttpServletRequest request,HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        if (cookies!=null&&cookies.length>0){
            Cookie rememberName = new Cookie("rememberName",null);
            rememberName.setMaxAge(0);
            rememberName.setPath(request.getContextPath()+"/");
            Cookie rememberPass = new Cookie("rememberPass",null);
            rememberPass.setMaxAge(0);
            rememberPass.setPath(request.getContextPath()+"/");
            response.addCookie(rememberName);
            response.addCookie(rememberPass);
        }
        String user = (String) session.getAttribute("user");
        session.invalidate();
        logger.info(user+"注销了!");
        return "redirect:/";
    }

    @PostMapping("/register")
    public String userRegister(User registerUser, HttpSession session){
        if(StringUtils.isEmpty(registerUser.getUserName())||StringUtils.isEmpty(registerUser.getPassword())||
                StringUtils.isEmpty(registerUser.getPhone())||StringUtils.isEmpty(registerUser.getEmail())||StringUtils.isEmpty(registerUser.getQq()))
            return "redirect:/register.html";
        if(userService.hasUser(registerUser.getUserName()))
            return "redirect:/register.html";
        registerUser.setCreatDate(new Date());
        if(userService.addUser(registerUser)) {
            session.setAttribute("user", registerUser.getUserName());
            logger.info(registerUser.getUserName()+"注册成功!");
            return "redirect:/";
        }else {
            logger.info("系统添加用户失败了!");
            return "redirect:/register.html";
        }
    }

}
